import axios from 'axios';

export interface UserLoginRequest {
  usernameOrEmail: string;
  password: string;
  rememberMe?: boolean;
  captcha?: string;
}

export interface UserRegisterRequest {
  userName: string;
  email: string;
  password: string;
  confirmPassword: string;
  name: string;
  surname: string;
  phoneNumber?: string;
  department?: string;
  position?: string;
}

export interface ChangePasswordRequest {
  currentPassword: string;
  newPassword: string;
  confirmNewPassword: string;
}

export interface ForgotPasswordRequest {
  email: string;
}

export interface ResetPasswordRequest {
  usernameOrEmail: string;
  resetToken: string;
  newPassword: string;
  confirmNewPassword: string;
}

export interface RefreshTokenRequest {
  refreshToken: string;
  userId: string;
}

export interface UserAuthResult {
  success: boolean;
  accessToken?: string;
  refreshToken?: string;
  tokenType?: string;
  expiresIn?: number;
  user?: UserInfo;
  errorMessage?: string;
  errorCode?: string;
}

export interface UserInfo {
  id: string;
  userName: string;
  email: string;
  name: string;
  surname: string;
  phoneNumber?: string;
  avatarUrl?: string;
  department?: string;
  position?: string;
  emailConfirmed: boolean;
  phoneNumberConfirmed: boolean;
  twoFactorEnabled: boolean;
  isAdmin: boolean;
  isActive: boolean;
  lastLoginTime?: string;
  roles: string[];
  permissions: string[];
}

class AuthService {
  private tokenKey = 'auth_token';
  private refreshTokenKey = 'refresh_token';
  private userKey = 'user_info';

  // 用户登录
  async login(loginRequest: UserLoginRequest): Promise<UserAuthResult> {
    try {
      const response = await axios.post('/api/auth/login', loginRequest);
      const result = response.data;

      if (result.success) {
        this.setAuthToken(result.accessToken);
        this.setRefreshToken(result.refreshToken);
        this.setUserInfo(result.user);
      }

      return result;
    } catch (error) {
      console.error('Login error:', error);
      return {
        success: false,
        errorMessage: '登录失败，请检查网络连接'
      };
    }
  }

  // 用户注册
  async register(registerRequest: UserRegisterRequest): Promise<UserAuthResult> {
    try {
      const response = await axios.post('/api/auth/register', registerRequest);
      const result = response.data;

      if (result.success) {
        this.setAuthToken(result.accessToken);
        this.setRefreshToken(result.refreshToken);
        this.setUserInfo(result.user);
      }

      return result;
    } catch (error) {
      console.error('Register error:', error);
      return {
        success: false,
        errorMessage: '注册失败，请检查网络连接'
      };
    }
  }

  // 用户登出
  async logout(): Promise<boolean> {
    try {
      await axios.post('/api/auth/logout');
      this.clearAuth();
      return true;
    } catch (error) {
      console.error('Logout error:', error);
      return false;
    }
  }

  // 刷新令牌
  async refreshToken(refreshTokenRequest: RefreshTokenRequest): Promise<UserAuthResult> {
    try {
      const response = await axios.post('/api/auth/refresh-token', refreshTokenRequest);
      const result = response.data;

      if (result.success) {
        this.setAuthToken(result.accessToken);
        this.setRefreshToken(result.refreshToken);
        this.setUserInfo(result.user);
      }

      return result;
    } catch (error) {
      console.error('Refresh token error:', error);
      this.clearAuth();
      return {
        success: false,
        errorMessage: '令牌刷新失败，请重新登录'
      };
    }
  }

  // 获取当前用户信息
  async getCurrentUser(): Promise<UserInfo | null> {
    try {
      const response = await axios.get('/api/auth/me');
      return response.data;
    } catch (error) {
      console.error('Get current user error:', error);
      return null;
    }
  }

  // 修改密码
  async changePassword(request: ChangePasswordRequest): Promise<boolean> {
    try {
      await axios.post('/api/auth/change-password', request);
      return true;
    } catch (error) {
      console.error('Change password error:', error);
      return false;
    }
  }

  // 忘记密码
  async forgotPassword(request: ForgotPasswordRequest): Promise<boolean> {
    try {
      await axios.post('/api/auth/forgot-password', request);
      return true;
    } catch (error) {
      console.error('Forgot password error:', error);
      return false;
    }
  }

  // 重置密码
  async resetPassword(request: ResetPasswordRequest): Promise<boolean> {
    try {
      await axios.post('/api/auth/reset-password', request);
      return true;
    } catch (error) {
      console.error('Reset password error:', error);
      return false;
    }
  }

  // 检查权限
  async hasPermission(permission: string): Promise<boolean> {
    try {
      const response = await axios.get('/api/auth/has-permission', {
        params: { permission }
      });
      return response.data;
    } catch (error) {
      console.error('Check permission error:', error);
      return false;
    }
  }

  // 检查角色
  async isInRole(role: string): Promise<boolean> {
    try {
      const response = await axios.get('/api/auth/is-in-role', {
        params: { role }
      });
      return response.data;
    } catch (error) {
      console.error('Check role error:', error);
      return false;
    }
  }

  // 启用双因子认证
  async enableTwoFactorAuth(): Promise<boolean> {
    try {
      const response = await axios.post('/api/auth/enable-2fa');
      return response.data;
    } catch (error) {
      console.error('Enable 2FA error:', error);
      return false;
    }
  }

  // 禁用双因子认证
  async disableTwoFactorAuth(): Promise<boolean> {
    try {
      const response = await axios.post('/api/auth/disable-2fa');
      return response.data;
    } catch (error) {
      console.error('Disable 2FA error:', error);
      return false;
    }
  }

  // 验证双因子认证码
  async verifyTwoFactorCode(code: string): Promise<boolean> {
    try {
      const response = await axios.post('/api/auth/verify-2fa', { code });
      return response.data;
    } catch (error) {
      console.error('Verify 2FA code error:', error);
      return false;
    }
  }

  // 确认邮箱
  async confirmEmail(token: string): Promise<boolean> {
    try {
      const response = await axios.post('/api/auth/confirm-email', { token });
      return response.data;
    } catch (error) {
      console.error('Confirm email error:', error);
      return false;
    }
  }

  // 重新发送邮箱确认邮件
  async resendEmailConfirmation(): Promise<boolean> {
    try {
      const response = await axios.post('/api/auth/resend-email-confirmation');
      return response.data;
    } catch (error) {
      console.error('Resend email confirmation error:', error);
      return false;
    }
  }

  // 确认电话号码
  async confirmPhoneNumber(code: string): Promise<boolean> {
    try {
      const response = await axios.post('/api/auth/confirm-phone', { code });
      return response.data;
    } catch (error) {
      console.error('Confirm phone number error:', error);
      return false;
    }
  }

  // 发送电话验证码
  async sendPhoneNumberVerification(): Promise<boolean> {
    try {
      const response = await axios.post('/api/auth/send-phone-verification');
      return response.data;
    } catch (error) {
      console.error('Send phone verification error:', error);
      return false;
    }
  }

  // 获取存储的认证令牌
  getAuthToken(): string | null {
    return localStorage.getItem(this.tokenKey);
  }

  // 获取存储的刷新令牌
  getRefreshToken(): string | null {
    return localStorage.getItem(this.refreshTokenKey);
  }

  // 获取存储的用户信息
  getUserInfo(): UserInfo | null {
    const userInfo = localStorage.getItem(this.userKey);
    return userInfo ? JSON.parse(userInfo) : null;
  }

  // 设置认证令牌
  private setAuthToken(token: string): void {
    localStorage.setItem(this.tokenKey, token);
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  }

  // 设置刷新令牌
  private setRefreshToken(token: string): void {
    localStorage.setItem(this.refreshTokenKey, token);
  }

  // 设置用户信息
  private setUserInfo(user: UserInfo): void {
    localStorage.setItem(this.userKey, JSON.stringify(user));
  }

  // 清除认证信息
  private clearAuth(): void {
    localStorage.removeItem(this.tokenKey);
    localStorage.removeItem(this.refreshTokenKey);
    localStorage.removeItem(this.userKey);
    delete axios.defaults.headers.common['Authorization'];
  }

  // 检查是否已认证
  isAuthenticated(): boolean {
    return !!this.getAuthToken();
  }

  // 检查是否是管理员
  isAdmin(): boolean {
    const userInfo = this.getUserInfo();
    return userInfo?.isAdmin || false;
  }

  // 检查是否有指定权限（基于本地存储的用户信息）
  hasPermissionLocal(permission: string): boolean {
    const userInfo = this.getUserInfo();
    return userInfo?.permissions?.includes(permission) || false;
  }

  // 检查是否有指定角色（基于本地存储的用户信息）
  isInRoleLocal(role: string): boolean {
    const userInfo = this.getUserInfo();
    return userInfo?.roles?.includes(role) || false;
  }

  // 获取用户显示名称
  getUserDisplayName(): string {
    const userInfo = this.getUserInfo();
    if (!userInfo) return '';
    return `${userInfo.name} ${userInfo.surname}`.trim() || userInfo.userName;
  }

  // 获取用户头像
  getUserAvatar(): string {
    const userInfo = this.getUserInfo();
    return userInfo?.avatarUrl || '';
  }

  // 刷新用户信息
  async refreshUserInfo(): Promise<void> {
    const userInfo = await this.getCurrentUser();
    if (userInfo) {
      this.setUserInfo(userInfo);
    }
  }

  // 自动刷新令牌
  async autoRefreshToken(): Promise<void> {
    const refreshToken = this.getRefreshToken();
    const userInfo = this.getUserInfo();
    
    if (refreshToken && userInfo) {
      try {
        await this.refreshToken({
          refreshToken,
          userId: userInfo.id
        });
      } catch (error) {
        console.error('Auto refresh token error:', error);
        this.clearAuth();
      }
    }
  }

  // 登出并清除所有认证信息
  async fullLogout(): Promise<void> {
    await this.logout();
    this.clearAuth();
    // 可选：重定向到登录页面
    window.location.href = '/login';
  }
}

// 导出单例实例
export const authService = new AuthService();

// 类型已在文件开头导出，无需重复导出

// 导出默认服务对象
export default authService;